const md5 = require('md5')
const {loginProjection,tokenSecret,tokenExpiresIn} = require('./../../kum.config')
const User = require('./../models/userSchema');
const jwt = require('jsonwebtoken')
const {success,fail,getPlaceByIp,delDifferentPlace,delDate} = require('./../utils/util')

module.exports =  {
  async login(params){
    try {
      // 合并查询项 需要额外查询邮箱和上次登录记录
      const needProject = [...loginProjection,'userEmail','lastLoginPlace','lastLoginIp','emailConfirmed']
      // 获取请求参数
      const {userName, userPwd,lastLoginIp } = params;
      // 查询数据库
      const res = await User.findOne({
        userName, userPwd: md5(userPwd)
      },needProject.join(' '))
      if(res){
        const data = res._doc;
        const token = jwt.sign({
          data
        },tokenSecret,{expiresIn:tokenExpiresIn})
        const lastLoginTime = new Date().getTime()


        // 获取本次登录的地址
        const lastLoginPlace = await getPlaceByIp(params.lastLoginIp);

        // 处理数据 去除不需要返回给前端的
        const resDate = delDate(loginProjection,data)
        resDate.token = token
        resDate.expiresIn = lastLoginTime+tokenExpiresIn

        await User.updateOne({userId:data.userId},{lastLoginIp,lastLoginTime,lastLoginPlace,token:token})

        // 处理ip和地区登录异常 并且告知用户邮件
        delDifferentPlace(data.userEmail,{place:data.lastLoginPlace,ip:data.lastLoginIp},{place:lastLoginPlace,ip:lastLoginIp},data.emailConfirmed)


        return success(resDate)
      }else{
       return fail('账号或者密码错误')
      }
    } catch(err){
      return fail(err.message)
    }
  },
  async register(params){
    try {
      const lastLoginTime = new Date().getTime()
      params.userPwd = md5(params.userPwd)
      params.lastLoginTime = lastLoginTime
      params.userId = md5(new Date()+params.userName)
      params.registerIp = params.lastLoginIp
      const place = await getPlaceByIp(params.lastLoginIp)
      params.registerPlace = place
      params.lastLoginPlace = place
      let user = new User({...params});
      const ret = await user.save()
      if(ret){
        let data = delDate(loginProjection,ret);
        data._id = ret._id
        const token = jwt.sign({
          data
        },tokenSecret,{expiresIn:tokenExpiresIn})
        data.expiresIn = lastLoginTime+tokenExpiresIn
        await User.updateOne({userId:data.userId},{token:token})
        return success(data)
      }else{
        return fail("注册失败")
      }
    } catch(err){
      return fail(err.message)
    }
  },

  async logout(token){
    const res = await User.updateOne({token:token},{token:""})
    if(res.modifiedCount===1){
      return success({msg:"退出成功",logout:true})
    }else{
      fail('退出失败')
    }
  }
}
